#include <INTRINS.h>
#include "ad.h"

#ifdef HAS_AD

static event_t	adc_event = 0;


void ADC_Isr() interrupt INTERRUPT_VECTOR_ADC
{
	ADC_INTERRUPT_FALG_CLEAR();
	event_post(adc_event);
}

void ad_init(event_t evt)
{
	adc_event = evt;
}

void ad_measure(unsigned char channel)
{
	ADC_ENABLE(channel);
	ADC_INTERRUPT_ENABLE();
	ADC_START();
}

unsigned int ad_get_result()
{
	return ADC_RESULT();
}

unsigned int ad_measure_and_get_result(unsigned char channel)
{
	ADC_ENABLE(channel);
	ADC_INTERRUPT_DISABLE();
	ADC_INTERRUPT_FALG_CLEAR();
	ADC_START();
	#if defined(SERIES_STC12C)
	_nop_();_nop_();_nop_();_nop_();
	#endif
	while(!ADC_INTERRUPT_FLAG_GET());
	ADC_INTERRUPT_FALG_CLEAR();
	return ADC_RESULT();
}

void ad_close()
{
	ADC_DISABLE();
}

#endif